#include "mystdio.h"
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

myFILE* my_fopen(const char* pathname,const char* mode)
{
   int flag=0;//
   //according mode define openmode
   if(strcmp(mode,"r")==0)
   {
     flag |= O_RDONLY;
   }
   else if(strcmp(mode,"w")==0)
   {
     flag |= O_WRONLY|O_CREAT|O_TRUNC;
   }
   else if(strcmp(mode,"a")==0)
   {
     flag |= O_WRONLY|O_CREAT|O_APPEND;
   }
   else
   {
     return NULL;// NULL --- open file failed
   }
   int fd=0;
   //"r" not exist write flag
   if(flag&O_WRONLY)//set write flag
   {
      umask(0);
      fd=open(pathname,flag,0666);
      //exist open file failed possibility
      if(fd < 0)
      {
        return NULL;
      }
   }
   else
   {
     fd=open(pathname,flag);
     if(fd<0)
     {
       return NULL;
     }
   }
   
   //creat struct FILE object
   myFILE* fp=(myFILE*)malloc(sizeof(myFILE));
   if(fp==NULL)
   {
     return NULL;
   }
   fp->fileno=fd;
   return fp;
}

void my_fclose(myFILE* fp)
{
   close(fp->fileno);
   free(fp);
}

int my_fwrite(myFILE* fp,const char* s,int size)
{
  return write(fp->fileno,s,size);
}












